//
//  BiModifyContentViewController.m
//  TrunkIndustryManageSystem
//
//  Created by WT_lyy on 15/5/5.
//  Copyright (c) 2015年 李璐西. All rights reserved.
//

#import "BiModifyContentViewController.h"

@interface BiModifyContentViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIActionSheetDelegate,UITextFieldDelegate>{

    __weak IBOutlet UIScrollView *_scrollview;
    __weak IBOutlet UILabel *_labVin;
    
    __weak IBOutlet UILabel *_labPasser;

    __weak IBOutlet UILabel *_labDiliverTime;
    __weak IBOutlet UILabel *_labStoreNum;
    __weak IBOutlet UILabel *_labStoreAddres;

    __weak IBOutlet UITextField *_textfReciever;
    
    __weak IBOutlet UITextField *_textfPerformance;

    NSInteger countIm;  //图片需上传计数
    NSInteger countUp; //图片上传完成计数
    
    NSMutableArray * _netImBtnArr; //网路图片按钮
    
    NSMutableArray * _locImBtnArr; //本地拍摄照片按钮
    
    NSMutableArray * _netImageObArr;
    
    BOOL isSave;
    
    NSInteger _index;  //纪录删除图片的索引
}

@property (weak, nonatomic) IBOutlet UIButton *btnImage;
@end

@implementation BiModifyContentViewController

- (id)init{
    
    self = [super init];
    
    if (self) {
        isSave = NO;
        
        _netImBtnArr = [NSMutableArray new];
        
        _locImBtnArr = [NSMutableArray new];
        
        _netImageObArr = [NSMutableArray new];
        
        countIm = 0;
        countUp = 0;
        
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setNavBackBtn];
    [self setNavBarTitle:@"合格证交付"];
    [self setNavBarWithHidden:NO];
    
    self.btnImage.layer.borderColor = UIColorFromRGB(ORANGE_COLOR_VALUE).CGColor;
    self.btnImage.layer.borderWidth = 1;
    self.btnImage.layer.cornerRadius = 3;
    
    [self dataFill];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    
    [self.view addGestureRecognizer:tap];
}

- (void)tapClick{
    
    [_textfReciever resignFirstResponder];
    
    [_textfPerformance resignFirstResponder];
}

- (void)dataFill{

    _labVin.text = self.mentity.vin;
    
    _labPasser.text = self.mentity.deliverHandlerName;
    
    _textfReciever.text = self.mentity.receiver;
    
    _labDiliverTime.text = self.mentity.deliverDate;
    
    _labStoreAddres.text = self.mentity.storeAddress;
    
    _labStoreNum.text = self.mentity.certificateCode;
    
    _textfPerformance.text = self.mentity.deliverPerformance;
    
    [_netImageObArr addObjectsFromArray:self.mentity.uploadImages];
    
    for (int i = 0; i < self.mentity.uploadImages.count; i++) {
        
        UIButton * imageViewtbn = [[UIButton alloc] initWithFrame:CGRectMake(5*(i+1)+i*(MAIN_SCREEN_WIDTH-20)/3, self.btnImage.frame.origin.y + self.btnImage.frame.size.height + 5, (MAIN_SCREEN_WIDTH-20)/3, (MAIN_SCREEN_WIDTH-20)/3)];
        [imageViewtbn addTarget:self action:@selector(btnImageClcik:) forControlEvents:UIControlEventTouchUpInside];
        imageViewtbn.tag = 100+i;
        
        [_netImBtnArr addObject:imageViewtbn];
        
        [imageViewtbn reloadImage:self.mentity.uploadImages[i]];
        
        [_scrollview addSubview:imageViewtbn];
        
    }
}

- (IBAction)btnUpCameroClick:(UIButton *)sender {
    
    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"相机功能不可用" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    picker.delegate = self;
    picker.allowsEditing = YES;
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)btnsaveClick:(UIButton *)sender {
    
    NSDictionary * paraDic = [NSDictionary dictionaryWithObjectsAndKeys:self.mentity.e_id,@"id",
                              _textfReciever.text,@"receiver",
                              _textfPerformance.text,@"deliverPerformance",nil];
    
    [[BiNetEngine shareInstance] requestCarModifySaveCertificate:self paraDict:paraDic];
    
    for (int i = 0; i<_locImBtnArr.count; i++) {
        
        UIImage * image = [_locImBtnArr[i] currentBackgroundImage];
        
        NSString * filename = [NSString stringWithFormat:@"%u",arc4random()+i];
        
        NSDictionary * paraDicIm = [NSDictionary dictionaryWithObjectsAndKeys:self.mentity.e_id,@"id",@"1",@"imgType",filename,@"fileName", nil];
        
        
        [[BiNetEngine shareInstance] requestCarModifyImage:self withImge:image paraDict:paraDicIm];
    }
    
    [self asyshowHUDView:WAITING CurrentView:self];
}


- (void)btnImageClcik:(UIButton *)butn{

    UIActionSheet* mySheet = [[UIActionSheet alloc]
                              initWithTitle:nil
                              delegate:self
                              cancelButtonTitle:@"取消"
                              destructiveButtonTitle:@"删除图片"
                              otherButtonTitles:@"查看大图",nil];
    [mySheet showInView:self.view];
    
    mySheet.tag = butn.tag;
}

#pragma -mark  UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    
    return YES;
}



#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSInteger index = actionSheet.tag%100;
    
    _index = index;
    
    switch (buttonIndex)
    {
        case 0:
        {  //删除图片
            
            if (actionSheet.tag < 200) { //网络图片
                
                NSDictionary * deleDic =[NSDictionary dictionaryWithObjectsAndKeys:self.mentity.e_id,@"id",[_netImageObArr[index] lastPathComponent],@"filePath",@"3",@"imgType", nil];
                
                [_netImageObArr removeObjectAtIndex:index];
                
                [[BiNetEngine shareInstance] requestModifyImageDelete:self paraDict:deleDic];
                
                [self asyshowHUDView:WAITING CurrentView:self];
                
            }else{//本地拍照
                
                NSInteger  indexLoc = index - _netImBtnArr.count;
                
                UIButton * nowbutn = _locImBtnArr[indexLoc];
                
                [nowbutn removeFromSuperview];
                
                [_locImBtnArr removeObjectAtIndex:indexLoc];
                
                for (int i = indexLoc; i< _locImBtnArr.count;i++) {
                    
                    UIButton * butn = _locImBtnArr[i];
                    
                    butn.tag --;
                    
                    butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
                }
            }
            
        }
            break;
        case 1:
        {  // 查看大图
            
            if (actionSheet.tag < 200) { //网络图片
                
                [BiUtil pusuToImageVc:self image:[_netImBtnArr[index] currentBackgroundImage] title:@"领条照片"];
            }else{//本地拍照
                
                [BiUtil pusuToImageVc:self image:[_locImBtnArr[(index-_netImBtnArr.count)] currentBackgroundImage] title:@"领条照片"];
            }
            
        }
            break;
        default:
            break;
    }
}


#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    NSInteger Count = _netImBtnArr.count + _locImBtnArr.count;
    
    if (Count == 3) {
        
        [self showMessage:@"亲，最多三张图片！"];
        
        return;
    }
    
    image = [BiUtil scaleToSize:image size:CGSizeMake(240, 200)];
    
    UIButton * imageViewtbn = [[UIButton alloc] initWithFrame:CGRectMake(5*(Count+1)+Count*(MAIN_SCREEN_WIDTH-20)/3, self.btnImage.frame.origin.y + self.btnImage.frame.size.height + 5, (MAIN_SCREEN_WIDTH-20)/3, (MAIN_SCREEN_WIDTH-20)/3)];
    
    [_scrollview addSubview:imageViewtbn];
    
    [imageViewtbn addTarget:self action:@selector(btnImageClcik:) forControlEvents:UIControlEventTouchUpInside];
    
    imageViewtbn.tag = 200+Count;
    
    [imageViewtbn setBackgroundImage:image forState:UIControlStateNormal];
    
    
    [_locImBtnArr addObject:imageViewtbn];
    
    countIm ++;
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma -mark Net Delegate
- (void)onNetEngineResponse:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    
    NSDictionary * entity_ = (NSDictionary *)entity;
    
    [self showMessage:entity_[@"result_info"]];
    
    if ([entity_[@"response_status"] integerValue] != 200) {
        
        [self removeHUDView:self];
        
        return;
        
    }
    switch (tag) {
        case NET_GET_CAR_MODIFY_SAVE:
            isSave = YES;
            break;
        case NET_GET_CAR_MODIFY_IMAGESAVE:
            countUp++;
            break;
        case NET_GET_CAR_MODIFY_IMAGEDEL:
        {
            //
            [self removeHUDView:self];
            UIButton * nowbtn = _netImBtnArr[_index];
            
            [nowbtn removeFromSuperview];
            
            [_netImBtnArr removeObjectAtIndex:_index];
            
            for (int i = _index; i< _netImBtnArr.count;i++) {
                
                UIButton * butn = _netImBtnArr[i];
                
                butn.tag --;
                
                butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
            }
            
            for (int i = 0; i< _locImBtnArr.count;i++) {
                
                UIButton * butn = _locImBtnArr[i];
                
                butn.tag --;
                
                butn.frame = CGRectMake(butn.frame.origin.x-butn.frame.size.width-5, butn.frame.origin.y, butn.frame.size.width, butn.frame.size.height);
            }
        }
            break;
        default:
            break;
    }
    
    if (isSave && (countUp == countIm)) {
        
        [self removeHUDView:self];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

- (void)onNetEngineResponseFail:(int)tag entity:(id)entity userInfo:(NSDictionary *)userInfo
{
    
    [self removeHUDView:self];
    
    [self showMessage:@"请求超时！"];
}

@end
